package com.tqz.rc.spring.cloud.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import com.tqz.rc.api.Instance;
import com.tqz.rc.client.naming.NamingService;
import com.tqz.rc.common.exception.RcException;
import com.tqz.rc.spring.cloud.discovery.TqzRcServiceDiscovery;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2021/9/9 11:03
 */
public class TqzRcServerList extends AbstractServerList<TqzRcServer> {

    private TqzRcServiceDiscovery tqzRcServiceDiscovery;

    private String serviceId;

    public TqzRcServerList(TqzRcServiceDiscovery tqzRcServiceDiscovery) {
        this.tqzRcServiceDiscovery = tqzRcServiceDiscovery;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        this.serviceId = clientConfig.getClientName();
    }

    @Override
    public List<TqzRcServer> getInitialListOfServers() {
        return getTqzRcServers();
    }

    @Override
    public List<TqzRcServer> getUpdatedListOfServers() {
        return getTqzRcServers();
    }

    /**
     * 获取 {@link TqzRcServer} 集合
     *
     * @return
     */
    private List<TqzRcServer> getTqzRcServers() {
        String groupName = tqzRcServiceDiscovery.getTqzRcProperties().getGroupName();
        NamingService namingService = tqzRcServiceDiscovery.getNamingService();

        List<Instance> instanceList = null;
        try {
            instanceList = namingService.selectInstances(serviceId, groupName);
        } catch (RcException e) {
            throw new IllegalStateException(
                    "Can not get service instances from TqzRc, serviceId=" + serviceId,
                    e);
        }

        return instanceToServerList(instanceList);
    }

    /**
     * 把获取的 {@link Instance} 集合转为 {@link TqzRcServer} 集合
     *
     * @param instances 实例集合
     * @return
     */
    private List<TqzRcServer> instanceToServerList(List<Instance> instances) {
        List<TqzRcServer> result = new ArrayList<>();

        if (instances == null || instances.size() <= 0) {
            return result;
        }

        for (Instance instance : instances) {
            result.add(new TqzRcServer(instance));
        }

        return result;
    }


}
